package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.vo.AccessToken;
import com.atguigu.common.vo.MemberRespVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.net.URI;
import java.net.URISyntaxException;

@Controller
public class Oauth2Controller {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private MemberFeignService memberFeignService;

    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws URISyntaxException {
        StringBuilder url = new StringBuilder("https://api.weibo.com/oauth2/access_token?");
        url.append("client_id=1914632292&");
        url.append("client_secret=faa5221230d0c51844e9277686bd5608&");
        url.append("grant_type=authorization_code&");
        url.append("redirect_uri=http://auth.gulimall.com/oauth2.0/weibo/success&");
        url.append("code="+code);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>( headers);
        ResponseEntity<AccessToken> responseEntity = restTemplate.postForEntity(url.toString(), httpEntity, AccessToken.class);

        if (responseEntity.getStatusCodeValue() == 200) {
            AccessToken accessToken = responseEntity.getBody();
            R r = memberFeignService.oauthLogin(accessToken);
            if (r.getCode() == 0) {
                MemberRespVo data = r.getData( new TypeReference<MemberRespVo>() {});
                System.out.println("登录成功"+data);
                session.setAttribute("loginUser",data);
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://gulimall.com";
        }
    }

}
